JAVAC=javac
JAR=jar
JAVA=java
EMULATOR=java -classpath $(EMU_JARS) org.microemu.app.Main
#-verbose:class 

EXPORT_FILE=password_composer_mini

PREVERIFY=$(LIB)/proguard-4.2.jar
MIDP_LIB=$(LIB)/midpapi20.jar
CLDC_LIB=$(LIB)/cldcapi10.jar
EMU_JARS=$(LIB)/microemulator-2.0.2.jar
LIB_JARS=$(LIB)/midpapi20.jar:$(LIB)/cldcapi10.jar

SOURCES=$(addprefix com.reftel.magnus.passwordcomposer., PasswordComposer) $(addprefix com.twmacinta.util., MD5 MD5State)
MANIFEST=passwordcomposer.mf

SRC=src
BUILD=build
LIB=lib
UNVERIFIED=$(BUILD)/unverified
PREVERIFIED=$(BUILD)/preverified
JARABLE=$(BUILD)/jarable
PREVERIFIED_CLASSES=$(addsuffix .class,$(subst .,/,$(addprefix $(PREVERIFIED)/, $(SOURCES))))
JARABLE_CLASSES=$(addsuffix .class,$(subst .,/,$(addprefix $(JARABLE)/, $(SOURCES))))
JARABLE_FILES=$(subst .,/,$(addprefix $(JARABLE)/, $(RESOURCES)))

JARNAME=passwordcomposer
JARFILES=$(BUILD)/$(JARNAME).jar
JADFILES=$(BUILD)/$(JARNAME).jad

.SUFFIXES:

all: $(JARFILES) $(JADFILES)

$(BUILD)/%.mf: $(SRC)/%.mf
	cp $< $@

$(BUILD)/$(JARNAME).jar: $(JARABLE_CLASSES) $(JARABLE_FILES) $(BUILD)/$(MANIFEST) | $(JARABLE)
	$(JAR) cfm $@ $(BUILD)/$(MANIFEST) -C $(JARABLE) .

$(BUILD)/$(JARNAME).jad: $(BUILD)/$(JARNAME).jar $(BUILD)/$(MANIFEST) 
	cp $(BUILD)/$(MANIFEST) $@
	echo MIDlet-Jar-URL: `basename $<` >> $@
	ls -l $< | awk '{printf "MIDlet-Jar-Size: %d\n", $$5}' >> $@

#build/unverified/%.class: src/%.java
#	$(JAVAC) -d $(UNVERIFIED) -sourcepath $(SRC) -classpath $(MIDP_LIB) $<

$(UNVERIFIED)/%.class: $(SRC)/java/%.java | $(UNVERIFIED)
	$(JAVAC) -Xlint -target 1.1 -source 1.2 -d $(UNVERIFIED) -sourcepath $(SRC)/java -classpath $(CLDC_LIB):$(MIDP_LIB) $<

$(PREVERIFIED)/%.class: $(UNVERIFIED)/%.class | $(PREVEIFIED)
	#$(JAVA) -jar $(PREVERIFY) @proguard.cfg
	java -jar lib/proguard-4.2.jar -microedition -injars $(UNVERIFIED) -outjars $(PREVERIFIED) -libraryjars $(LIB_JARS) -dontshrink -dontoptimize -dontobfuscate

$(JARABLE)/%: $(SRC)/resources/common/% | $(JARABLE)
	if [ ! -d `dirname $@` ]; then mkdir -p `dirname $@`; fi
	cp $< $@

$(JARABLE)/%: $(PREVERIFIED)/% | $(JARABLE)
	if [ ! -d `dirname $@` ]; then mkdir -p `dirname $@`; fi
	cp $< $@

$(UNVERIFIED): $(BUILD)
	if [ ! -d $@ ]; then mkdir $@; fi

$(PREVERIFIED): $(BUILD)
	if [ ! -d $@ ]; then mkdir $@; fi

$(BUILD):
	if [ ! -d $@ ]; then mkdir $@; fi

$(JARABLE) : $(BUILD)
	if [ ! -d $@ ]; then mkdir $@; fi

clean:
	-rm -r $(BUILD)

run: $(BUILD)/$(JARNAME).jad
	$(EMULATOR) -appclasspath $(LIB_JARS):$< file:$(BUILD)/$(JARNAME).jad

export: $(EXPORT_FILE)-$(shell bzr revno).zip

$(EXPORT_FILE)-$(shell bzr revno).zip:
	bzr export $@
